import TWEEN from './tween.js';

var ZW_Ctx;
var angle = 0;
var ZW_PicArray = [];
var goodsArray = [];
var ZW_Offset = 30;
var ZW_PointsArray = [];
var ZW_Info;
var ZW_PixelRatio = 2;
var gIsIphone = false;

var ZW_ClickNodeName = '';
var ZW_HoldNodeName = '';       //长按得珠子名称
var ZW_HoldIndex = 0;   //长按得珠子所在的索引值
var ZW_bHold = false;
var ZW_bLoading = false;  //是否正在加载图片

var Scene_OffsetX = 0;
var Scene_OffsetY = 0;

var Scene_ScaleX = 1.0;
var Scene_ScaleY = 1.0;

var ZW_ClickPos;

var ZW_CurrentPos = 0;

var ZW_Close_Url = '../../../img/close.png';
var ZW_Scale_Url = '../../../img/scale.png';
var ZW_Rot_Url = '../../../img/rotation.png';

var ZW_bTipEdit = true;

var ZW_MoveType = '';

var ZW_tipArray = []; //贴纸名称数组，需要保证不重复
var ZW_tipNumArray = [];  //用于贴纸加载时的计数
var that;
function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}


function AddChain(tag, url) {
  //AddImage(tag,url,ZW_Info.windowWidth/2,150,200,200,0,1.0);

  AddImage(tag, url, 0, 100, ZW_Info.windowHeight * 0.7882, ZW_Info.windowHeight, 0, 1.0);
}



function AddImage(tag, url, x, y, width, height, rot, scale, visible, order) {
  RemoveImage(tag);
  if (!order) order = 0;
  let contentPicNetPath = url;

  var cImage = { tag: tag, x: x, y: y, width: width, height: height, url: '', rot: rot, scale: scale, visible: visible, renderOrder: order };
  ZW_PicArray.push(cImage);

  jd.getImageInfo({
    //保存网络图片
    src: contentPicNetPath,
    success:
      function (res) {
        cImage.url = res.path;

        //ZW_PicArray.push({tag:tag,x:x,y:y,width:width,height:height,url:res.path,rot:rot,scale:scale});
        //console.log(ZW_PicArray);
      }
  })
}


function AddExpression(name) {

  for (var i = 0; i < 5; i++) {
    RemoveImage('expression-' + i);
  }

  //   AddImage('expression1', 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/expression/ex2/female02-0.png', ZW_Info.windowWidth * 0.5, ZW_Info.windowWidth * 0.85,
  //   ZW_Info.windowWidth * 0.5 * 1.4, ZW_Info.windowWidth * 1.4, 0, 1.0,true);

  var gifUrlArray = [];
  for (var i = 0; i < 5; i++) {
    gifUrlArray.push(name + '-' + i + '.png');

    if (i == 0) {
      AddGifImage1('expression-' + i, gifUrlArray[i], ZW_Info.windowWidth * 0.526, ZW_Info.windowWidth * 0.462,
        ZW_Info.windowWidth * 0.5333 * 0.55, ZW_Info.windowWidth * 0.42666 * 0.55, 0, 1.0, false, 4);
    } else {
      AddGifImage1('expression-' + i, gifUrlArray[i], ZW_Info.windowWidth * 0.526, ZW_Info.windowWidth * 0.462,
        ZW_Info.windowWidth * 0.5333 * 0.55, ZW_Info.windowWidth * 0.42666 * 0.55, 0, 1.0, false, 4);
    }

  }
}

//判断2d点是否在三角形中。x0, y0，为检测点。剩余三个点，为三角形的三个点。当返回结果为true，则检测点在三角形上。如果为false，则点不在三角形上。
function PointInTriangle(x0, y0, x1, y1, x2, y2, x3, y3) {
  var divisor = (y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3);
  var a = ((y2 - y3) * (x0 - x3) + (x3 - x2) * (y0 - y3)) / divisor;
  var b = ((y3 - y1) * (x0 - x3) + (x1 - x3) * (y0 - y3)) / divisor;
  var c = 1 - a - b;

  return a >= 0 && a <= 1 && b >= 0 && b <= 1 && c >= 0 && c <= 1;
}

//通过坐标点返回点击的类型
function GetTipBtnType(tag, x0, y0) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (ZW_PicArray[i].tag.indexOf(tag + '-') > -1) {
      var posX = ZW_PicArray[i].x0;
      var posY = ZW_PicArray[i].y0;
      var width = ZW_PicArray[i].width * ZW_PicArray[i].scale0;
      var height = ZW_PicArray[i].height * ZW_PicArray[i].scale0;
      var pDis = Math.sqrt((width * width) + (height * height));

      var rad1 = Math.asin(height / pDis) + Math.PI * ZW_PicArray[i].rot0 / 180.0;

      var posX1 = posX - 0.5 * pDis * Math.cos(rad1);
      var posY1 = posY - 0.5 * pDis * Math.sin(rad1);

      var rad2 = (Math.PI - Math.asin(height / pDis)) + Math.PI * ZW_PicArray[i].rot0 / 180.0;

      var posX2 = posX - 0.5 * pDis * Math.cos(rad2);
      var posY2 = posY - 0.5 * pDis * Math.sin(rad2);

      var rad3 = (Math.PI + Math.asin(height / pDis)) + Math.PI * ZW_PicArray[i].rot0 / 180.0;

      var posX3 = posX - 0.5 * pDis * Math.cos(rad3);
      var posY3 = posY - 0.5 * pDis * Math.sin(rad3);

      var rad4 = (2 * Math.PI - Math.asin(height / pDis)) + Math.PI * ZW_PicArray[i].rot0 / 180.0;

      var posX4 = posX - 0.5 * pDis * Math.cos(rad4);
      var posY4 = posY - 0.5 * pDis * Math.sin(rad4);


      var pDis1 = Math.sqrt(((x0 - posX1) * (x0 - posX1)) + ((y0 - posY1) * (y0 - posY1)));
      var pDis2 = Math.sqrt(((x0 - posX2) * (x0 - posX2)) + ((y0 - posY2) * (y0 - posY2)));
      var pDis3 = Math.sqrt(((x0 - posX3) * (x0 - posX3)) + ((y0 - posY3) * (y0 - posY3)));

      if (pDis1 < 30) {
        return 'remove';
      } else if (pDis2 < 30) {
        return 'scale';
      } else if (pDis3 < 30) {
        return 'rotation';
      } else {
        return '';
      }

      //return [{x:posX1,y:posY1},{x:posX2,y:posY2},{x:posX3,y:posY3},{x:posX4,y:posY4}];
    }
  }
}

//通过点的位置来获取贴纸的tag值
function GetTipTagByPoint(point) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    for (var j = ZW_tipArray.length - 1; j > -1; j--) {
      if (ZW_PicArray[i].tag == ZW_tipArray[j] + '-0') {
        var posX = ZW_PicArray[i].x0;
        var posY = ZW_PicArray[i].y0;
        var width = ZW_PicArray[i].width * ZW_PicArray[i].scale0;
        var height = ZW_PicArray[i].height * ZW_PicArray[i].scale0;
        var pDis = Math.sqrt((width * width) + (height * height));

        var rad1 = Math.asin(height / pDis) + Math.PI * ZW_PicArray[i].rot0 / 180.0;

        var posX1 = posX - 0.5 * pDis * Math.cos(rad1);
        var posY1 = posY - 0.5 * pDis * Math.sin(rad1);

        var rad2 = (Math.PI - Math.asin(height / pDis)) + Math.PI * ZW_PicArray[i].rot0 / 180.0;

        var posX2 = posX - 0.5 * pDis * Math.cos(rad2);
        var posY2 = posY - 0.5 * pDis * Math.sin(rad2);

        var rad3 = (Math.PI + Math.asin(height / pDis)) + Math.PI * ZW_PicArray[i].rot0 / 180.0;

        var posX3 = posX - 0.5 * pDis * Math.cos(rad3);
        var posY3 = posY - 0.5 * pDis * Math.sin(rad3);

        var rad4 = (2 * Math.PI - Math.asin(height / pDis)) + Math.PI * ZW_PicArray[i].rot0 / 180.0;

        var posX4 = posX - 0.5 * pDis * Math.cos(rad4);
        var posY4 = posY - 0.5 * pDis * Math.sin(rad4);

        var pDis1 = Math.sqrt(((point.x - posX1) * (point.x - posX1)) + ((point.y - posY1) * (point.y - posY1)));
        var pDis2 = Math.sqrt(((point.x - posX2) * (point.x - posX2)) + ((point.y - posY2) * (point.y - posY2)));
        var pDis3 = Math.sqrt(((point.x - posX3) * (point.x - posX3)) + ((point.y - posY3) * (point.y - posY3)));


        var result = PointInTriangle(point.x, point.y, posX1, posY1, posX2, posY2, posX3, posY3) ||
          PointInTriangle(point.x, point.y, posX1, posY1, posX3, posY3, posX4, posY4) || pDis1 < 30 || pDis2 < 30 || pDis3 < 30;

        if (result) return ZW_tipArray[j];
      }
    }
  }
  return '';
  // for (var i = 0; i < ZW_PicArray.length; i++) {
  //   if(ZW_PicArray[i].tag.indexOf('tip'+index) > -1)
  //   {
  //     var posX = ZW_PicArray[i].x0;
  //     var posY = ZW_PicArray[i].y0;
  //     var width = ZW_PicArray[i].width*ZW_PicArray[i].scale0;
  //     var height = ZW_PicArray[i].height*ZW_PicArray[i].scale0;
  //     var pDis = Math.sqrt((width * width) + (height * height));

  //     var rad1 = Math.asin(height/pDis)+Math.PI*ZW_PicArray[i].rot0/180.0;

  //     var posX1 = posX-0.5*pDis*Math.cos(rad1);
  //     var posY1 = posY-0.5*pDis*Math.sin(rad1);

  //     var rad2 = (Math.PI -Math.asin(height/pDis))+Math.PI*ZW_PicArray[i].rot0/180.0;

  //     var posX2 = posX-0.5*pDis*Math.cos(rad2);
  //     var posY2 = posY-0.5*pDis*Math.sin(rad2);

  //     var rad3 = (Math.PI +Math.asin(height/pDis))+Math.PI*ZW_PicArray[i].rot0/180.0;

  //     var posX3 = posX-0.5*pDis*Math.cos(rad3);
  //     var posY3 = posY-0.5*pDis*Math.sin(rad3);

  //     var rad4 = (2*Math.PI -Math.asin(height/pDis))+Math.PI*ZW_PicArray[i].rot0/180.0;

  //     var posX4 = posX-0.5*pDis*Math.cos(rad4);
  //     var posY4 = posY-0.5*pDis*Math.sin(rad4);

  //     return [{x:posX1,y:posY1},{x:posX2,y:posY2},{x:posX3,y:posY3},{x:posX4,y:posY4}];
  //   }
  // }
}

//获取贴纸的四个点的位置
function GetTipPoints(tag) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (ZW_PicArray[i].tag.indexOf(tag + '-') > -1) {
      var posX = ZW_PicArray[i].x0;
      var posY = ZW_PicArray[i].y0;
      var width = ZW_PicArray[i].width * ZW_PicArray[i].scale0;
      var height = ZW_PicArray[i].height * ZW_PicArray[i].scale0;
      var pDis = Math.sqrt((width * width) + (height * height));

      var rad1 = Math.asin(height / pDis) + Math.PI * ZW_PicArray[i].rot0 / 180.0;

      var posX1 = posX - 0.5 * pDis * Math.cos(rad1);
      var posY1 = posY - 0.5 * pDis * Math.sin(rad1);

      var rad2 = (Math.PI - Math.asin(height / pDis)) + Math.PI * ZW_PicArray[i].rot0 / 180.0;

      var posX2 = posX - 0.5 * pDis * Math.cos(rad2);
      var posY2 = posY - 0.5 * pDis * Math.sin(rad2);

      var rad3 = (Math.PI + Math.asin(height / pDis)) + Math.PI * ZW_PicArray[i].rot0 / 180.0;

      var posX3 = posX - 0.5 * pDis * Math.cos(rad3);
      var posY3 = posY - 0.5 * pDis * Math.sin(rad3);

      var rad4 = (2 * Math.PI - Math.asin(height / pDis)) + Math.PI * ZW_PicArray[i].rot0 / 180.0;

      var posX4 = posX - 0.5 * pDis * Math.cos(rad4);
      var posY4 = posY - 0.5 * pDis * Math.sin(rad4);

      return [{ x: posX1, y: posY1 }, { x: posX2, y: posY2 }, { x: posX3, y: posY3 }, { x: posX4, y: posY4 }];
    }
  }
}


//设置场景中的贴纸是否编辑
function SetEditState(bEdit) {
  ZW_bTipEdit = bEdit;
}

//获取贴纸的位置
function GetTipPosition(tag) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (ZW_PicArray[i].tag.indexOf(tag + '-') > -1) {
      return [ZW_PicArray[i].x0, ZW_PicArray[i].y0];
    }
  }
}

//设置贴纸的位置
function SetTipPosition(tag, x, y) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (ZW_PicArray[i].tag.indexOf(tag + '-') > -1) {
      ZW_PicArray[i].x0 = x;
      ZW_PicArray[i].y0 = y;
    }
  }
}

//获取贴纸的旋转值
function GetTipRotation(tag) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (ZW_PicArray[i].tag.indexOf(tag + '-') > -1) {
      return ZW_PicArray[i].rot0;
    }
  }
}

//设置贴纸的旋转值
function SetTipRotation(tag, rot) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (ZW_PicArray[i].tag.indexOf(tag + '-') > -1) {
      ZW_PicArray[i].rot0 = rot;

    }
  }
}

//获取贴纸的缩放
function GetTipScale(tag) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (ZW_PicArray[i].tag.indexOf(tag + '-') > -1) {
      return ZW_PicArray[i].scale0;
    }
  }
}

//设置贴纸的缩放
function SetTipScale(tag, scale) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (ZW_PicArray[i].tag.indexOf(tag + '-') > -1) {
      ZW_PicArray[i].scale0 = scale;

    }
  }
}


//删除贴纸
function RemoveTip(tag) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (ZW_PicArray[i].tag.indexOf(tag + '-') > -1) {
      ZW_PicArray.splice(i, 1);
      i--;
    }
  }

  for (var i = 0; i < ZW_tipArray.length; i++) {
    if (ZW_tipArray[i].indexOf(tag) > -1) {
      ZW_tipArray.splice(i, 1);
      ZW_tipNumArray.splice(i, 1);
      i--;
    }
  }
}

function AddTip(tag, url, num, width, height, x, y, rot, scale) {
  if (!x) x = 0;
  if (!y) y = 0;
  //var gifUrlArray = [];
  ZW_tipArray.push(tag);
  ZW_tipNumArray.push(num);
  for (var i = 0; i < num; i++) {
    //  gifUrlArray.push(url +'-'+ i + '.png');

    var rUrl = url + '-' + i + '.png';
    console.log(rUrl);
    AddGifImage2(tag, rUrl, x, y, width * 0.3, height * 0.3, rot, scale, true, num, 9, i);

  }
}

function AddGifImage2(tag, url, x, y, width, height, rot, scale, visible, num1, order, index) {
  let contentPicNetPath = url;

  //var cImage = { tag: tag, x: x, y: y, width: width, height: height, url: '', rot: rot, scale: scale ,visible:visible,renderOrder:order,type:'tip'};

  var cImage = { tag: tag + '-' + index, x: 0, y: 0, x0: x, y0: y, width: width, height: height, url: '', rot: 0, rot0: rot, scale: scale, scale0: 1.0, visible: visible, renderOrder: order, type: 'tip' };

  ZW_PicArray.push(cImage);

  jd.getImageInfo({
    //保存网络图片
    src: contentPicNetPath,
    success:
      function (res) {
        cImage.url = res.path;

        for (var i = 0; i < ZW_tipArray.length; i++) {
          if (ZW_tipArray[i] == tag) {
            ZW_tipNumArray[i] = ZW_tipNumArray[i] - 1;

            if (ZW_tipNumArray[i] == 0) {
              console.log('gif is over');
              var coords = { x: 0 };
              new TWEEN.Tween(coords)
                .to({ x: num1 }, 1000 * num1 / 4.0)
                .repeat(Infinity)
                .easing(TWEEN.Easing.Linear.None)
                .onUpdate(function () {
                  var num = Math.round(coords.x) % num1;

                  for (var j = 0; j < num1; j++) {
                    SetImageVisible(tag + '-' + j, false);
                  }

                  SetImageVisible(tag + '-' + num, true);

                })
                .delay(0)
                .start();
            }
          }
        }
      }
  })
}

function addBackgroundByData(inData) {
  RemoveImage('back1');

  AddGifImage('back1', app.globalData.baseUrl + inData.scenebackGifImage,
    ZW_Info.windowWidth * 0.5, ZW_Info.windowWidth * 0.5 * 2.16533,
    ZW_Info.windowWidth, ZW_Info.windowWidth * 2.16533, 0, 1.0, false, 0);

  that.setData({
    backGifUrl: app.globalData.baseUrl + inData.scenebackGifUrl,
    backBottomUrl: app.globalData.baseUrl + inData.sceneBackBottomUrl,
  });

}

function AddBackgroud(type) {

  RemoveImage('back1');

  if (type == 1) {
    AddGifImage('back1', 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/bg1.jpg', ZW_Info.windowWidth * 0.5, ZW_Info.windowWidth * 0.5 * 2.16533,
      ZW_Info.windowWidth, ZW_Info.windowWidth * 2.16533, 0, 1.0, false, 0);

    that.setData({
      backGifUrl: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/bg1.gif',
      backBottomUrl: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/BG1-bottom.jpg'
    });
  } else if (type == 2) {
    AddGifImage('back1', 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/bg2.jpg', ZW_Info.windowWidth * 0.5, ZW_Info.windowWidth * 0.5 * 2.16533,
      ZW_Info.windowWidth, ZW_Info.windowWidth * 2.16533, 0, 1.0, false, 0);

    that.setData({
      backGifUrl: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/bg2.gif',
      backBottomUrl: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/BG2-bottom.jpg'
    });
  } else if (type == 3) {
    AddGifImage('back1', 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/bg3.jpg', ZW_Info.windowWidth * 0.5, ZW_Info.windowWidth * 0.5 * 2.16533,
      ZW_Info.windowWidth, ZW_Info.windowWidth * 2.16533, 0, 1.0, false, 0);

    that.setData({
      backGifUrl: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/bg3.gif',
      backBottomUrl: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/BG3-bottom.jpg'
    });

  } else if (type == 4) {
    AddGifImage('back1', 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/bg4.jpg', ZW_Info.windowWidth * 0.5, ZW_Info.windowWidth * 0.5 * 2.16533,
      ZW_Info.windowWidth, ZW_Info.windowWidth * 2.16533, 0, 1.0, false, 0);

    that.setData({
      backGifUrl: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/bg4.gif',
      backBottomUrl: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/BG4-bottom.jpg'
    });
  } else if (type == 5) {
    AddGifImage('back1', 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/bg4.jpg', ZW_Info.windowWidth * 0.5, ZW_Info.windowWidth * 0.5 * 2.16533,
      ZW_Info.windowWidth, ZW_Info.windowWidth * 2.16533, 0, 1.0, false, 0);

    that.setData({
      backGifUrl: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/bg4.gif',
      backBottomUrl: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif1/BG4-bottom.jpg'
    });
  }
}

function AddGifImage(tag, url, x, y, width, height, rot, scale, visible, order) {
  let contentPicNetPath = url;

  var cImage = { tag: tag, x: x, y: y, width: width, height: height, url: '', rot: rot, scale: scale, visible: visible, renderOrder: order };
  ZW_PicArray.unshift(cImage);


  jd.getImageInfo({
    //保存网络图片
    src: contentPicNetPath,
    success:
      function (res) {
        cImage.url = res.path;
      }
  })
}

var Load_URL_Num = 0;
var Load_URL_Num0 = 0;
var expressionTween = null;

var G_Count = 0;

function AddGifImage1(tag, url, x, y, width, height, rot, scale, visible, order) {
  let contentPicNetPath = url;

  var cImage = { tag: tag, x: x, y: y, width: width, height: height, url: '', rot: rot, scale: scale, visible: visible, renderOrder: order };
  ZW_PicArray.push(cImage);

  Load_URL_Num0++;

  jd.getImageInfo({
    //保存网络图片
    src: contentPicNetPath,
    success:
      function (res) {
        cImage.url = res.path;

        Load_URL_Num0--;
        if (Load_URL_Num0 == 0) {

          var coords = { x: 4 };
          if (expressionTween) {
            expressionTween.stop();
            expressionTween = null;
          }
          expressionTween = new TWEEN.Tween(coords)
            .to({ x: 0 }, 1000 * 0.6)
            .repeat(Infinity).repeatDelay(5000)
            .easing(TWEEN.Easing.Linear.None)
            .onUpdate(function () {
              var num = Math.round(coords.x) % 5;

              for (var i = 4; i > -1; i--) {
                SetImageVisible('expression-' + i, false);
              }

              SetImageVisible('expression-' + num, true);
            })
            .delay(0)
            .start();
        }
      }
  })
}

function RemoveImage(tag) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (tag == ZW_PicArray[i].tag) {
      ZW_PicArray.splice(i, 1);
      i--;
    }
  }
}


function SetImageVisible(tag, visible) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (tag == ZW_PicArray[i].tag) {
      ZW_PicArray[i].visible = visible;
    }
  }
}


function SetImageScale(tag, scale) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (tag == ZW_PicArray[i].tag) {
      ZW_PicArray[i].scale = scale;
    }
  }
}

function SetImageUrl(tag, url) {
  let contentPicNetPath = url;

  // var cImage = {tag:tag,x:x,y:y,width:width,height:height,url:'',rot:rot,scale:scale};
  // ZW_PicArray.push(cImage);

  if (url == '') {    //不显示某些部件
    for (var i = 0; i < ZW_PicArray.length; i++) {
      if (tag == ZW_PicArray[i].tag) {
        ZW_PicArray[i].url = '';
      }
    }
  }

  jd.getImageInfo({
    //保存网络图片
    src: contentPicNetPath,
    success:
      function (res) {
        for (var i = 0; i < ZW_PicArray.length; i++) {
          if (tag == ZW_PicArray[i].tag) {
            ZW_PicArray[i].url = res.path;

            // jd.showToast({
            //   title: '替换',
            //   icon: 'success',
            //   duration: 1500
            // })
          }
        }
        //cImage.url = res.path;
        // ZW_PicArray.push({tag:tag,x:x,y:y,width:width,height:height,url:res.path,rot:rot,scale:scale});
        //console.log(ZW_PicArray);

      }
  })
}

//松开手指的处理
function ReleaseProcess() {

}

//改变视角
function ChangeView(type) {
  if(type == 'top')
  {
    var coords = { x: Scene_OffsetX, y: Scene_OffsetY, x1: Scene_ScaleX, y1: Scene_ScaleY };
    new TWEEN.Tween(coords)
      .to({ x: -ZW_Info.windowWidth * 0.08, y: +ZW_Info.windowWidth * 0.1, x1: 1.2, y1: 1.2 }, 250)
      .repeat(0)
      .easing(TWEEN.Easing.Linear.None)
      .onUpdate(function () {
        Scene_OffsetX = coords.x;
        Scene_OffsetY = coords.y;
        Scene_ScaleX = coords.x1;
        Scene_ScaleY = coords.y1;
      })
      .delay(0)
      .start();
  }else if(type == 'center')
  {
    var coords = { x: Scene_OffsetX, y: Scene_OffsetY, x1: Scene_ScaleX, y1: Scene_ScaleY };
    new TWEEN.Tween(coords)
      .to({ x: 0, y: 0, x1: 1.0, y1: 1.0 }, 250)
      .repeat(0)
      .easing(TWEEN.Easing.Linear.None)
      .onUpdate(function () {
        Scene_OffsetX = coords.x;
        Scene_OffsetY = coords.y;
        Scene_ScaleX = coords.x1;
        Scene_ScaleY = coords.y1;
      })
      .delay(0)
      .start();
  }else if(type == 'bottom')
  {
    var coords = { x: Scene_OffsetX, y: Scene_OffsetY, x1: Scene_ScaleX, y1: Scene_ScaleY };
    new TWEEN.Tween(coords)
      .to({ x: -ZW_Info.windowWidth * 0.08, y: -ZW_Info.windowWidth * 0.4, x1: 1.2, y1: 1.2 }, 250)
      .repeat(0)
      .easing(TWEEN.Easing.Linear.None)
      .onUpdate(function () {
        Scene_OffsetX = coords.x;
        Scene_OffsetY = coords.y;
        Scene_ScaleX = coords.x1;
        Scene_ScaleY = coords.y1;
      })
      .delay(0)
      .start();
  }
}


//距离计算公式
function M_distance(a, b) {
  var x = b[0] - a[0],
    y = b[1] - a[1],
    z = b[2] - a[2];
  return Math.sqrt(x * x + y * y + z * z);
};

//角度计算公式
function M_GetAngle(v0, v1, v2) {
  var linev0v1 = M_distance(v0, v1);
  var linev0v2 = M_distance(v0, v2);
  var linev1v2 = M_distance(v1, v2);

  return Math.acos((linev0v1 * linev0v1 + linev1v2 * linev1v2 - linev0v2 * linev0v2) / (2 * linev0v1 * linev1v2)) * 180.0 / 3.1415926;
}

function StartDecorationAnimation(tag, index1, index2, time) {
  //console.log(index1+'++++'+index2);
  if (!time) time = 300;
  var coords = { x: index1 };
  new TWEEN.Tween(coords)
    .to({ x: index2 }, time)
    .repeat(0)
    .easing(TWEEN.Easing.Linear.None)
    .onUpdate(function () {

    })
    .delay(0)
    .start();
}

function GetNodeByTag(tag) {
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (ZW_PicArray[i].tag == tag) {
      return ZW_PicArray[i];
    }
  }
  return null;
}

function ShowProcess() {
  ZW_PicArray.sort(function (a, b) { return a.renderOrder - b.renderOrder });

  ZW_Ctx.scale(Scene_ScaleX, Scene_ScaleY);
  for (var i = 0; i < ZW_PicArray.length; i++) {
    if (ZW_PicArray[i].url != '' && ZW_PicArray[i].visible) {

      if (ZW_PicArray[i].type == 'tip') {
        let contentPicLocalPath = ZW_PicArray[i].url;

        ZW_Ctx.translate(ZW_PicArray[i].x0 + Scene_OffsetX, ZW_PicArray[i].y0 + Scene_OffsetY);
        ZW_Ctx.rotate(ZW_PicArray[i].rot0 * Math.PI / 180);
        ZW_Ctx.scale(ZW_PicArray[i].scale0, ZW_PicArray[i].scale0);

        ZW_Ctx.translate(ZW_PicArray[i].x, ZW_PicArray[i].y);
        ZW_Ctx.drawImage(contentPicLocalPath, -ZW_PicArray[i].scale * ZW_PicArray[i].width / 2,
          -ZW_PicArray[i].scale * ZW_PicArray[i].height / 2, ZW_PicArray[i].width * ZW_PicArray[i].scale, ZW_PicArray[i].height * ZW_PicArray[i].scale);

        if (ZW_bTipEdit && ZW_PicArray[i].tag.indexOf(Current_Tip_Tag + '-') == 0) {  //只有选中的贴纸才显示边框和按钮
          //贴纸画框
          ZW_Ctx.setStrokeStyle("#ffffff");
          ZW_Ctx.setLineWidth(2.0 / ZW_PicArray[i].scale0);
          ZW_Ctx.rect(-ZW_PicArray[i].scale * ZW_PicArray[i].width / 2,
            -ZW_PicArray[i].scale * ZW_PicArray[i].height / 2, ZW_PicArray[i].width * ZW_PicArray[i].scale, ZW_PicArray[i].height * ZW_PicArray[i].scale);
          ZW_Ctx.stroke();

          //画删除按钮
          ZW_Ctx.drawImage(ZW_Close_Url, -ZW_PicArray[i].scale * ZW_PicArray[i].width / 2 - 12.0 / ZW_PicArray[i].scale0,
            -ZW_PicArray[i].scale * ZW_PicArray[i].height / 2 - 12.0 / ZW_PicArray[i].scale0, 24.0 / ZW_PicArray[i].scale0, 24.0 / ZW_PicArray[i].scale0);

          //画缩放按钮
          ZW_Ctx.drawImage(ZW_Scale_Url, ZW_PicArray[i].width * ZW_PicArray[i].scale - ZW_PicArray[i].scale * ZW_PicArray[i].width / 2 - 12.0 / ZW_PicArray[i].scale0,
            -ZW_PicArray[i].scale * ZW_PicArray[i].height / 2 - 12.0 / ZW_PicArray[i].scale0, 24.0 / ZW_PicArray[i].scale0, 24.0 / ZW_PicArray[i].scale0);

          //画旋转按钮
          ZW_Ctx.drawImage(ZW_Rot_Url, ZW_PicArray[i].width * ZW_PicArray[i].scale - ZW_PicArray[i].scale * ZW_PicArray[i].width / 2 - 12.0 / ZW_PicArray[i].scale0,
            ZW_PicArray[i].height * ZW_PicArray[i].scale - ZW_PicArray[i].scale * ZW_PicArray[i].height / 2 - 12.0 / ZW_PicArray[i].scale0, 24.0 / ZW_PicArray[i].scale0, 24.0 / ZW_PicArray[i].scale0);
        }

        ZW_Ctx.translate(-ZW_PicArray[i].x, -ZW_PicArray[i].y);

        ZW_Ctx.scale(1.0 / ZW_PicArray[i].scale0, 1.0 / ZW_PicArray[i].scale0);
        ZW_Ctx.rotate(-ZW_PicArray[i].rot0 * Math.PI / 180);
        ZW_Ctx.translate(-ZW_PicArray[i].x0 - Scene_OffsetX, -ZW_PicArray[i].y0 - Scene_OffsetY);
      } else {
        let contentPicLocalPath = ZW_PicArray[i].url;

        ZW_Ctx.translate(ZW_PicArray[i].x + Scene_OffsetX, ZW_PicArray[i].y + Scene_OffsetY);
        ZW_Ctx.rotate(ZW_PicArray[i].rot * Math.PI / 180);
        ZW_Ctx.drawImage(contentPicLocalPath, -ZW_PicArray[i].scale * ZW_PicArray[i].width / 2,
          -ZW_PicArray[i].scale * ZW_PicArray[i].height / 2, ZW_PicArray[i].width * ZW_PicArray[i].scale, ZW_PicArray[i].height * ZW_PicArray[i].scale);
        ZW_Ctx.rotate(-ZW_PicArray[i].rot * Math.PI / 180);
        ZW_Ctx.translate(-ZW_PicArray[i].x - Scene_OffsetX, -ZW_PicArray[i].y - Scene_OffsetY);
      }
    }

  }
  ZW_Ctx.draw();
}

function animation() {
  var times = 0
  var i = setInterval(function () {

    // //console.log('sss');
    // gStage.update();
    //angle++;
    // let contentPicLocalPath = "/img/t1.png"
    // ZW_Ctx.translate(20, 50);
    // ZW_Ctx.rotate(angle * Math.PI / 180);
    // ZW_Ctx.drawImage(contentPicLocalPath, -20, -50, 40, 100)

    // ZW_Ctx.translate(200, 200);
    // ZW_Ctx.rotate(-angle * Math.PI / 180);
    // ZW_Ctx.drawImage(contentPicLocalPath, -50, -50, 100, 100)

    TWEEN.update();

    ShowProcess();
  }, 20)
}


var Current_Tip_Tag = '';

var Current_Tip_Rot = 0;

var Current_Back_Index = 1;

var testIndex = 1;


// import testMenuData from "../../utils/testMenuData.js"
var app = getApp();
let tipLinesForChangeGender = ["更改性别会丢失","现在的搭配哦"];
let tipLinesForChangeTiger = ["换成老虎会丢失","现在的肤色和发型哦"];
Page({
  data: {
    baseUrl: app.globalData.baseUrl,
    listerListInfo: [],
    leftValue1: 0,
    canvasWidth: 360,
    canvasHeight: 360,

    // 右侧部件组合菜单数据
    rightMenuData: [],
    // 右侧已选部件组合id
    rightMenuId: 0,
    // backGifUrl: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif/bg1.gif',
    // backBottomUrl: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/gif/BG1-bottom.jpg',

    backGifUrl: '',
    backBottomUrl: '',

    pageStatus: 0, // 0:eidt  1:finish

    shotImageUrl: '',

    // 备选部件菜单
    gPartsMenuDatas: {},

    // 切换性别时，是否需要提示
    needResetConfirm: true,
    showQueryDialog: false,
    queryParam: {},
    queryDialogStr1:'',
    queryDialogStr2:'',
  },

  onReady: function () {
    this.setData({
      gPartsMenuDatas: app.globalData.gPartsMenuDatas,
      rightMenuData: app.globalData.gPartsMenuDatas.rightMenuItemData
    })
    // 注册底部组件
    this.bottomMenuView = this.selectComponent("#bottomview"); //组件的id
    this.rightMenuView = this.selectComponent("#rightmenu"); //组件的id

    ZW_Ctx = jd.createCanvasContext('canvas')

    ZW_Info = jd.getSystemInfoSync();
    console.log(ZW_Info);
    gIsIphone = ZW_Info.platform == "ios";

    ZW_PixelRatio = ZW_Info.pixelRatio;

    this.setData({
      canvasWidth: ZW_Info.windowWidth,
      canvasHeight: ZW_Info.windowHeight * 0.7,
    });

    that = this;
    // AddBackgroud(app.globalData.sceneBackgroundId);

    let backData = app.globalData.gShowBodyLays.find(e => {
      return e.partId == "background"
    })
    addBackgroundByData(backData);

    for (let i = 0; i < app.globalData.gShowBodyLays.length; i++) {
      let temp = app.globalData.gShowBodyLays[i];
      if (temp.partId == "background")
        continue;

      if (temp.partId != "expression") {
        AddImage(
          temp.partId,
          this.data.baseUrl + temp.partImage,
          ZW_Info.windowWidth * 0.5, ZW_Info.windowWidth * 0.827,
          ZW_Info.windowWidth * 1.3, ZW_Info.windowWidth * 1.3,
          0, 1.0,
          true, i + 1);
      } else {
        AddExpression(this.data.baseUrl + temp.partSourcePath);
      }
    }

    animation();

    // 右侧菜单选中第一个
    this.rightMenuView.setDefaultItem(0);
  },

  onUnload: function () {
    clearInterval(this.interval);
  },
  onTouchStart(e) {
    //console.log(e);
    if (gIsIphone) {
      // ZW_PixelRatio = 1;
      // e.touches[0].y -= ZW_Info.screenHeight - ZW_Info.windowHeight;
    }
    var clickPos = { x: e.touches[0].x, y: e.touches[0].y };

    ZW_ClickPos = { x: e.touches[0].x, y: e.touches[0].y };

    // jd.showToast({
    //   title: e.touches[0].y.toString() +','+ e.touches[0].y.toString(),
    //   icon: 'success',
    //   duration: 1500
    // })
    var cTag = GetTipTagByPoint(ZW_ClickPos);


    Current_Tip_Tag = cTag;
    var points = GetTipPoints(Current_Tip_Tag);

    var result = PointInTriangle(ZW_ClickPos.x, ZW_ClickPos.y, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y) ||
      PointInTriangle(ZW_ClickPos.x, ZW_ClickPos.y, points[0].x, points[0].y, points[2].x, points[2].y, points[3].x, points[3].y);

    var type = GetTipBtnType(Current_Tip_Tag, ZW_ClickPos.x, ZW_ClickPos.y);

    if (type == '') {
      if (result) {
        ZW_MoveType = 'position';
      }
    } else {
      if (type == 'scale') {
        ZW_MoveType = 'scale';
      } else if (type == 'rotation') {
        ZW_MoveType = 'rotation';
      }
      else if (type == 'remove') {
        RemoveTip(Current_Tip_Tag);
      } else {
        // jd.showToast({
        //   title: type,
        //   icon: 'success',
        //   duration: 500
        // })
      }
    }

    //ChangeView('bottom');
    //AddBackgroud(4);

    // ChangeView('top');
    // SetImageUrl('body', 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/body/body03.png');

    // SetImageUrl('cloth', 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_vansdress_jd/jacket/jacket01.png');
    // SetImageUrl('hat', '');


    setTimeout(() => {
      ZW_ClickNodeName = '';
    }, 350);

    setTimeout(() => {
      this.longTap(e);
    }, 500);
  },
  onTouchMove(e) {
    if (gIsIphone) {
      // ZW_PixelRatio = 1;
      // e.touches[0].y -= ZW_Info.screenHeight - ZW_Info.windowHeight;
    }


    var clickPos = { x: e.touches[0].x, y: e.touches[0].y };

    if (ZW_MoveType != '') {
      var xOffset = clickPos.x - ZW_ClickPos.x;
      var yOffset = clickPos.y - ZW_ClickPos.y;

      if (ZW_MoveType == 'position') {
        var testPos = GetTipPosition(Current_Tip_Tag);
        SetTipPosition(Current_Tip_Tag, testPos[0] + xOffset, testPos[1] + yOffset);
      } else if (ZW_MoveType == 'rotation') {
        var testPos = GetTipPosition(Current_Tip_Tag);

        //计算角度
        let A = { X: testPos[0], Y: testPos[1] }
        let B = { X: clickPos.x, Y: clickPos.y }
        let C = { X: ZW_ClickPos.x, Y: ZW_ClickPos.y }
        var AB = Math.sqrt(Math.pow(A.X - B.X, 2) + Math.pow(A.Y - B.Y, 2));
        var AC = Math.sqrt(Math.pow(A.X - C.X, 2) + Math.pow(A.Y - C.Y, 2));
        var BC = Math.sqrt(Math.pow(B.X - C.X, 2) + Math.pow(B.Y - C.Y, 2));
        var cosA = (
          Math.pow(AB, 2) + Math.pow(AC, 2) - Math.pow(BC, 2)
        ) / (
            2 * AB * AC
          );
        var angleA = Math.round(Math.acos(cosA) * 180 / Math.PI);


        //计算是否为顺时针
        var bAdd = true;

        var p1 = { x: ZW_ClickPos.x, y: ZW_ClickPos.y };
        var p2 = { x: testPos[0], y: testPos[1] };
        var p3 = { x: clickPos.x, y: clickPos.y };
        bAdd = ((p1.x - p3.x) * (p2.y - p3.y) - (p1.y - p3.y) * (p2.x - p3.x)) < 0;

        var testRot = GetTipRotation(Current_Tip_Tag);
        if (bAdd) {
          testRot += angleA;
        } else {
          testRot -= angleA;
        }

        SetTipRotation(Current_Tip_Tag, testRot);

      } else if (ZW_MoveType == 'scale') {
        var testPos = GetTipScale(Current_Tip_Tag);
        if (xOffset > 0) {
          SetTipScale(Current_Tip_Tag, testPos * 1.05);
        } else {
          SetTipScale(Current_Tip_Tag, testPos * 0.95);
        }

      }
    }

    ZW_ClickPos = { x: e.touches[0].x, y: e.touches[0].y };

    //console.log(e.touches[0].x / ZW_PixelRatio - ZW_ClickPos.x);

    //ZW_CurrentPos += (e.touches[0].x - ZW_ClickPos.x) ;


    //ZW_ClickPos.x = e.touches[0].x / ZW_PixelRatio;

    // if (ZW_HoldNodeName != '') {
    //   var clickPos = { x: e.touches[0].x / ZW_PixelRatio, y: e.touches[0].y / ZW_PixelRatio };

    //   //var resultIndex = -1;
    //   var resultDis = 100000;

    //   for (var i = 0; i < ZW_PointsArray[0].length; i++) {
    //     var dis = M_distance([ZW_PointsArray[0][i].x, ZW_PointsArray[0][i].y, 0], [clickPos.x, clickPos.y, 0]);
    //     if (dis < resultDis) {
    //       resultDis = dis;
    //       ZW_HoldIndex = i;
    //     }
    //   }
    // }
  },
  onTouchEnd(e) {
    //console.log(e);

    ZW_MoveType = '';

    ZW_bHold = false;
    if (ZW_HoldNodeName != '') {
      ReleaseProcess();
      ZW_HoldNodeName = '';
    }
  },
  onTouchCancel(e) {
    //console.log(e);
  },
  longTap(e) {

    if (!ZW_bHold) return;
    // console.log(e);
    if (gIsIphone) {
      ZW_PixelRatio = 1;
      //e.touches[0].y -= ZW_Info.screenHeight-ZW_Info.windowHeight;
    }

  },

  onFinishClick() {
    console.log("onFinishClick")
    this.setData({
      pageStatus: 1
    })
  },

  onGetShot(inType) {
    // 将生成的canvas图片，转为真实图片
    //console.log("onGetShot() ----------------------");
    jd.showLoading();
    let _self = this;
    SetImageVisible('back1', true);  //显示背景图
    SetEditState(false);  //隐藏编辑框
    ShowProcess();

    setTimeout(() => {
      jd.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: ZW_Info.windowWidth,
        height: ZW_Info.windowWidth * 1.76,
        canvasId: 'canvas',
        success: function (resp) {
          jd.saveImageToPhotosAlbum({
            filePath: resp.tempFilePath,
            success(res) {
              jd.hideLoading();
              SetImageVisible('back1', false);
              SetEditState(true); //显示原来的编辑框
              ShowProcess();

              jd.showToast({
                title: '保存成功',
                icon: 'success',
                duration: 1500
              })

              _self.data.shotImageUrl = resp.tempFilePath;
              console.log("onGetShot === " + inType)
              if (inType == "share") {
                console.log("onGetShot === showShare " + inType)
                // jd.showShareMenu({
                //   success: (e) => {
                //     console.log("jd  share  ok", e)
                //   },
                //   fail: (e) => {
                //     console.log("jd  share  fail", e)
                //   }
                // })
                console.log("onGetShot === navigateTo " + '../../sharePage/sharePage?shotImagePath=' + _self.data.shotImageUrl)
                jd.navigateTo({
                  url: '../../sharePage/sharePage?shotImagePath=' + _self.data.shotImageUrl
                })
              }
            }
          })
        },
        fail: function (res) {
          jd.showToast({
            title: '截图失败'
          })
        }
      });
    }, 1000);


    return;
  },


  /////////////////////////////////////////////////////////////////////////////////////////////////////


  updateBodyParts() {
    console.log("============updateBodyParts", app.globalData.gShowBodyLays)
    for (let i = 0; i < app.globalData.gShowBodyLays.length; i++) {
      let temp = app.globalData.gShowBodyLays[i];
      if (temp.partId == "background") {
        console.log("-.-.-.-change background-.-.--.")
        console.log(temp)
        addBackgroundByData(temp);
      }
      else if (temp.partId == "tips") {
        if (temp.partSrcId && temp.partSrcId.length > 0) {
          var tipTag = guid();
          Current_Tip_Tag = tipTag;
          let tempPath = temp.partSourcePath;
          AddTip(Current_Tip_Tag, this.data.baseUrl + tempPath, 6, 480, 480, ZW_Info.windowWidth * 0.5, ZW_Info.windowWidth * 0.5, 0, 1.0);
          temp.partSrcId = '';
          temp.partImage = '';
          temp.partSourcePath = '';
        }
      }
      else if (temp.partId != "expression") {
        SetImageUrl(
          temp.partId,
          temp.partImage && temp.partImage.length > 0 ? this.data.baseUrl + temp.partImage : '');
        console.log(`updateBodyParts   ${temp.partId}   ${temp.partImage && temp.partImage.length > 0 ? this.data.baseUrl + temp.partImage : ''}`)
      }
      else {
        AddExpression(this.data.baseUrl + temp.partSourcePath);
      }
    }
  },

  /**
   * 右侧菜单按钮选择
   * @param {*} e 
   */
  onRightMenuItemChange(e) {
    console.log("onRightMenuItemChange" + e.detail.selectItemId)
    this.setData({
      rightMenuId: e.detail.selectItemId
    })

    let _self = this;
    let rightData = this.data.rightMenuData.find(e => {
      return e.id == _self.data.rightMenuId
    });

    if(rightData) {
      ChangeView(rightData.moveAnim)
    }

    this.bottomMenuView.setSelectRightMenuId(e.detail.selectItemId);
  },

  /**
   * 重置性别默认最简着装
   * @param {*} inGender 
   */
  resetGenderData(inGender) {
    let bodyLays = app.globalData.gShowBodyLays;
    let tempHairId = null;

    for (let i = 0; i < bodyLays.length; i++) {
      if (bodyLays[i].resetType == -1) {
        // 不处理部件
      } else if (bodyLays[i].resetType == 0) {
        // 清空
        bodyLays[i].partImage = "";
        bodyLays[i].partGifImage = "";
        bodyLays[i].partSourcePath = "";
        bodyLays[i].partSrcId = null;
      } else if (bodyLays[i].resetType == 1) {
        // 找到性别相关的默认部件候选
        let defaultData = this.data.gPartsMenuDatas[bodyLays[i].partId].find(e => {
          return e.sexy == inGender || e.sexy == 3
          // if (inGender == 0)
          //   return e.isMaleDefault;
          // else if (inGender == 1)
          //   return e.isFemaleDefault;
          // else if (inGender == 2)
          //   return e.isNoneDefault;
        })

        if (defaultData) {
          bodyLays[i].partSrcId = defaultData.dataId;
          bodyLays[i].partImage = defaultData.srcUrl;
          if (defaultData.sourcePath)
            bodyLays[i].partSourcePath = defaultData.sourcePath;

          if (bodyLays[i].partId == "bangs") {
            // tempHairId = defaultData.hairId;
            tempHairId = defaultData.detailDataId;
          }
        }
      }
    }

    if (tempHairId && tempHairId.length > 0) {
      let defaultHairData = this.data.gPartsMenuDatas["hair"].find(e => {
        return e.dataId == tempHairId
      })

      for (let i = 0; i < bodyLays.length; i++) {
        if (bodyLays[i].partId == 'hair') {
          if (defaultHairData) {
            bodyLays[i].partSrcId = defaultHairData.dataId;
            bodyLays[i].partImage = defaultHairData.srcUrl;
            if (defaultHairData.sourcePath)
              bodyLays[i].partSourcePath = defaultHairData.sourcePath;
          } else {
            bodyLays[i].partSrcId = '';
            bodyLays[i].partImage = '';
            bodyLays[i].partSourcePath = '';
          }
        }
      }
    } else {
      for (let i = 0; i < bodyLays.length; i++) {
        if (bodyLays[i].partId == 'hair') {
          bodyLays[i].partSrcId = '';
          bodyLays[i].partImage = '';
          bodyLays[i].partSourcePath = '';
        }
      }
    }
    app.globalData.gShowBodyLays = bodyLays;
    // 更换性别后 再换性别不弹框
    this.setData({
      needResetConfirm: false
    })
  },

  /**
   * 备选构件click
   * @param {*} inData 
   */
  onCandidateClick(inData) {
    console.log("onCandidateClick", inData.detail)
    let tempInId = inData.detail.classifyId;
    let tempInPartData = inData.detail.selectItem;

    if (tempInId == "sexyList") {
      let tempToGender = inData.detail.selectItem.dataId;
      if (app.globalData.selectGender == tempToGender) {
        return;
      }

      if (this.data.needResetConfirm) {
        this.setData({
          showQueryDialog: true,
          queryParam: tempToGender,
          queryDialogStr1: tipLinesForChangeGender[0],
          queryDialogStr2: tipLinesForChangeGender[1]
        })
      } else {
        app.globalData.selectGender = tempToGender;
        this.resetGenderData(tempToGender)
        this.updateBodyParts();
      }
    } else {
      let tempPart = app.globalData.gShowBodyLays.find(item => {
        return item.partId == tempInId
      })

      console.log(tempPart)

      if (tempPart) {
        if (tempPart.partId == "background") {
          tempPart.partSrcId = tempInPartData.dataId;


          tempPart.partSrcId = tempInPartData.dataId;
          tempPart.imageUrl = tempInPartData.imageUrl;
          tempPart.frameUrl = tempInPartData.frameUrl;
          tempPart.gifUrl = tempInPartData.gifUrl;

          tempPart.scenebackGifImage = tempInPartData.scenebackGifImage;
          tempPart.scenebackGifUrl = tempInPartData.scenebackGifUrl;
          tempPart.sceneBackBottomUrl = tempInPartData.sceneBackBottomUrl;



        }
        // else if (tempPart.partId == "tips") {
        //   tempPart.partSrcId = tempInPartData.dataId;
        //   tempPart.partImage = tempInPartData.srcUrl;
        //   if (tempInPartData.sourcePath)
        //     tempPart.partSourcePath = tempInPartData.sourcePath;
        // }
        else {
          tempPart.partSrcId = tempInPartData.dataId;
          tempPart.partImage = tempInPartData.srcUrl;
          if (tempInPartData.sourcePath)
            tempPart.partSourcePath = tempInPartData.sourcePath;
        }
      }

      if (tempPart && tempPart.partId == 'bangs') {
        let tempHairId = tempInPartData.detailDataId;
        let defaultHairData = this.data.gPartsMenuDatas["hair"].find(e => {
          return e.dataId == tempHairId
        })

        let tempHairPart = app.globalData.gShowBodyLays.find(item => {
          return item.partId == "hair"
        })

        if (defaultHairData) {
          tempHairPart.partSrcId = defaultHairData.dataId;
          tempHairPart.partImage = defaultHairData.srcUrl;
          if (defaultHairData.sourcePath)
            tempHairPart.partSourcePath = defaultHairData.sourcePath;
        } else {
          tempHairPart.partSrcId = "";
          tempHairPart.partImage = "";
          tempHairPart.partSourcePath = "";
        }


        // for (let i = 0; i < bodyLays.length; i++) {
        //   if (bodyLays[i].partId == 'hair') {
        //     if (defaultHairData) {
        //       bodyLays[i].partSrcId = defaultHairData.dataId;
        //       bodyLays[i].partImage = defaultHairData.srcUrl;
        //       if (defaultHairData.sourcePath)
        //         bodyLays[i].partSourcePath = defaultHairData.sourcePath;
        //     } else {
        //       bodyLays[i].partSrcId = '';
        //       bodyLays[i].partImage = '';
        //       bodyLays[i].partSourcePath = '';
        //     }
        //   }
        // }
      }
      // console.log(tempPart)

      // if (tempInId != "expression")
      //   SetImageUrl(tempInId, this.data.baseUrl + tempPart.partImage);
      // else {
      //   console.log(this.data.baseUrl + tempPart.partSourcePath)
      //   AddExpression(this.data.baseUrl + tempPart.partSourcePath);
      // }
      this.updateBodyParts();

      if(tempPart != "skin") {
        this.setData({
          needResetConfirm: true
        })
      }
    }
  },

  onToShareClick() {
    console.log("== share ===")
    this.onGetShot("share");
  },

  onToDiyClick() {
    console.log("== onToDiyClick ===")
    this.setData({
      pageStatus: 0
    })
  },

  onToAddCartClick() {
    console.log("== onToAddCartClick ===")
    let temp = [];
    app.globalData.gShowBodyLays.forEach(element => {
      if (element.partDesc)
        temp.push(element)
    });

    if (temp.length == 0) {
      jd.showToast({
        title: "没有可选的商品。"
      })
      return;
    }

    jd.navigateTo({
      url: "../../addCartPage/addCartPage?dataStr=" + JSON.stringify(temp)
    })
  },

  onToAddMyClick() {
    console.log("== onToAddMyClick ===")
  },

  onQueryConfirm(e) {
    console.log(e.detail)
    this.setData({
      showQueryDialog: false,
      queryParam: ''
    })

    app.globalData.selectGender = e.detail;
    this.resetGenderData(e.detail)
    this.updateBodyParts();
  },

  onQueryCancel(e) {
    this.setData({
      showQueryDialog: false,
      queryParam: ''
    })
  }
});